<!-- answer.html -->
<!DOCTYPE html>
<html>
<head>
    <title>千年匠心·腐乳的制作密码</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
</head>
<body class="answer-page">
    <div class="container">
        <div class="progress-bar">
            <div class="progress" id="progress"></div>
        </div>
        <div class="question-card" id="questionContainer"></div>

        <div class="answer-box">
            <input type="text" id="answerInput" placeholder="输入答案（多个用逗号分隔）" style="display:none;">
        </div>

        <div class="nav-buttons">
            <button class="btn prev-btn" onclick="previousQuestion()">◀ 回炉重造</button>
            <button class="btn submit-btn" onclick="checkAnswer()">🍶 装坛密封</button>
        </div>
        <div class="score-board" id="scoreDisplay">当前得分：0分</div>
    </div>
    <script src="questions.js"></script>
    <script>
        let currentQ = 0;
        let totalScore = 0;
        let userAnswers = {};
        
        const difficulty = localStorage.getItem('selectedDifficulty');
        const quiz = questions[difficulty];
        const progressBar = document.getElementById('progress');

        // 初始化显示
        showQuestion();
        updateProgress();

        function updateProgress() {
            const percent = ((currentQ + 1) / quiz.length) * 100;
            progressBar.style.width = `${percent}%`;
        }

        

        // 修改 showQuestion 函数
        function showQuestion() {
            const q = quiz[currentQ];
            const answerInput = document.getElementById('answerInput');
            
            // 清空状态
            answerInput.style.display = 'none';
            answerInput.value = '';
            document.querySelectorAll('input').forEach(input => input.checked = false);

            // 生成题目内容
            let optionsHTML = '';
            switch(q.type) {
                case 'single':
                    optionsHTML = q.options.map(opt => `
                        <label class="option">
                            <input type="radio" name="answer" value="${opt[0]}">
                            ${opt}
                        </label>`).join('');
                    break;
                case 'multi':
                    optionsHTML = q.options.map(opt => `
                        <label class="option">
                            <input type="checkbox" name="answer" value="${opt[0]}">
                            ${opt}
                        </label>`).join('');
                    break;
                case 'judge':
                    optionsHTML = `
                        <label class="option">
                            <input type="radio" name="answer" value="✔">
                            ✔ 正确
                        </label>
                        <label class="option">
                            <input type="radio" name="answer" value="✖">
                            ✖ 错误
                        </label>`;
                    break;
                case 'fill':
                    answerInput.style.display = 'block';
                    answerInput.placeholder = "填空题，请输入答案（多个答案用逗号分隔）";
                    break;
            }

            // 注入DOM
            document.getElementById('questionContainer').innerHTML = `
                <div class="question-header">
                    <span>第 ${currentQ + 1} 题</span>
                    <span>(${q.score}分)</span>
                </div>
                <div class="question-text">${q.question}</div>
                ${q.type !== 'fill' ? `<div class="options">${optionsHTML}</div>` : ''}
                ${q.hint ? `<div class="hint">💡 提示：${q.hint}</div>` : ''}`;

            // ==== 关键修复：在DOM生成后恢复答案 ====
            if (userAnswers[currentQ] !== null) {
                if (q.type === 'fill') {
                    answerInput.value = userAnswers[currentQ];
                    answerInput.style.display = 'block';
                } else {
                    const answerValues = userAnswers[currentQ]?.split(',') || [];
                    answerValues.forEach(val => {
                        const input = document.querySelector(`input[value="${val.trim()}"]`);
                        if (input) {
                            if (input.type === 'checkbox') {
                                input.checked = true;
                            } else {
                                input.checked = true;
                            }
                        }
                    });
                }
            }
        }

                // 修改 checkAnswer 函数的计分逻辑部分
        function checkAnswer() {
            saveCurrentAnswer();
            const q = quiz[currentQ];
            let userAnswer = '';

            // 获取用户答案（保持原逻辑）
            switch(q.type) {
                case 'single':
                case 'judge':
                    userAnswer = (document.querySelector('input[name="answer"]:checked')?.value || '').trim();
                    break;
                case 'multi':
                    userAnswer = [...document.querySelectorAll('input[name="answer"]:checked')]
                                .map(input => input.value.trim())
                                .sort() // 增加排序
                                .join(',');
                    break;
                case 'fill':
                    userAnswer = document.getElementById('answerInput').value
                                .replace(/，/g, ',')
                                .split(',')
                                .map(item => item.trim())
                                .filter(item => item)
                                .sort() // 增加排序
                                .join(',');
                    break;
            }

            // 处理正确答案
            let correctAnswer;
            if(Array.isArray(q.answer)) {
                correctAnswer = q.answer
                                .map(a => a.trim())
                                .sort() // 保持排序一致
                                .join(',');
            } else {
                correctAnswer = q.answer.trim();
            }

            // 调试输出
            console.log('用户答案:', userAnswer);
            console.log('正确答案:', correctAnswer);

            // 严格比对答案（区分大小写）
            if(userAnswer === correctAnswer) {
                totalScore += q.score;
                document.getElementById('scoreDisplay').classList.add('correct');
                setTimeout(() => {
                    document.getElementById('scoreDisplay').classList.remove('correct');
                }, 1000);
            }

            // 更新得分显示
            document.getElementById('scoreDisplay').textContent = `当前得分：${totalScore}分`;

            // 切换题目
            if(currentQ < quiz.length - 1) {
                currentQ++;
                showQuestion();
                updateProgress();
            } else {
                showResult();
            }
        }
        function saveCurrentAnswer() {
            const q = quiz[currentQ];
            let answer = '';
            
            // 获取当前答案
            switch(q.type) {
                case 'single':
                case 'judge':
                    answer = document.querySelector('input[name="answer"]:checked')?.value || '';
                    break;
                case 'multi':
                    answer = [...document.querySelectorAll('input[name="answer"]:checked')]
                            .map(input => input.value).join(',');
                    break;
                case 'fill':
                    answer = document.getElementById('answerInput').value;
                    break;
            }
            
            // 用当前题号保存答案（关键）
            userAnswers[currentQ] = answer;
        }
        function previousQuestion() {
    if (currentQ > 0) {
        // 保存当前答案
        const q = quiz[currentQ];
        let currentAnswer = '';
        
        switch(q.type) {
            case 'single':
            case 'judge':
                currentAnswer = document.querySelector('input[name="answer"]:checked')?.value || '';
                break;
            case 'multi':
                currentAnswer = [...document.querySelectorAll('input[name="answer"]:checked')]
                            .map(input => input.value).join(',');
                break;
            case 'fill':
                currentAnswer = document.getElementById('answerInput').value;
                break;
        }
        userAnswers[currentQ] = currentAnswer;

        // 切换题目
        currentQ--;
        showQuestion();
        updateProgress();
    }
}

            function showResult() {
                // 添加结果页背景class
                document.body.classList.add('result-page-bg');
                // 移除原有答题页面背景
                document.body.classList.remove('answer-page');

                document.getElementById('questionContainer').innerHTML = `
                    <div class="result-card">
                        <h2>发酵完成</h2>
                        <div class="final-score">
                        <span class="score-text">您的得分是：</span>
                        <span class="score-number">${totalScore}</span>
                        <span class="score-unit">分</span>
                        </div>
                        <p>${getResultComment()}</p>
                        <button onclick="window.location.href='index.html'" class="btn">
                            🏮 返回祖坊
                        </button>
                    </div>
                `;
                
                // 隐藏不需要的元素
                document.querySelector('.answer-box').style.display = 'none';
                document.querySelector('.nav-buttons').style.display = 'none';
                document.querySelector('.progress-bar').style.display = 'none';
                
                // 修改容器样式
                document.querySelector('.container').style.background = 'transparent';
            }

                function getResultComment() {
                    if (totalScore >= 80) return "您已获得「腐乳宗师」称号！";
                    if (totalScore >= 60) return "合格掌缸人，继续精进！";
                    return "还需潜心修炼传统工艺";
                }
            
            // 在 answer.html 中添加以下代码
window.addEventListener('DOMContentLoaded', () => {
    const audio = document.getElementById('bgMusic');
    const saved = JSON.parse(sessionStorage.getItem('musicSession') || '{}');
    
    // 恢复核心状态
    audio.volume = saved.volume || 0.3;
    audio.currentTime = saved.currentTime || 0;

    // 自动播放策略
    const tryPlay = () => {
        if (saved.isPlaying) {
            audio.play().catch(error => {
                console.log('播放失败:', error);
                document.getElementById('musicAlert').style.display = 'block';
            });
        }
    };

    // 桌面端直接尝试
    if (!/Mobi|Android/i.test(navigator.userAgent)) tryPlay();

    // 移动端交互处理
    let needsTap = true;
    const handleTap = () => {
        if (needsTap) {
            tryPlay();
            needsTap = false;
            document.getElementById('musicAlert').style.display = 'none';
        }
    };
    document.addEventListener('click', handleTap);
    document.addEventListener('touchstart', handleTap);
});

// 实时保存状态
setInterval(() => {
    const audio = document.getElementById('bgMusic');
    sessionStorage.setItem('musicSession', JSON.stringify({
        isPlaying: !audio.paused,
        currentTime: audio.currentTime,
        volume: audio.volume
    }));
}, 500); // 更频繁的保存
            </script>
        <audio id="bgMusic" loop crossorigin="anonymous">
            <source src="music/bgmusic.mp3" type="audio/mpeg">
        </audio>
    
        </body>
        </html>